package com.vmix.android.vmixsdk.rds;

import com.vmix.android.vmixsdk.exception.VmixException;
import com.vmix.android.vmixsdk.valueobject.VmixVideos;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class GetMediaListService extends Service {
	
	public static final String MEDIA_FOUND = "media_found";
	
	protected GetMediaListOperation operation = null;
	
	private VmixVideos videos = null;
	
	private String collectionId = "";
	
	public GetMediaListService( String collectionId ) {
		
		this.collectionId = collectionId;
		
	}
	
	@Override
	public void onCreate() {
		// TODO
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		// Retrieve the shared preferences
		// Context context = getApplicationContext();
		
		// String getMediaListUrl = getString( R.string.MEDIA);
		// this.updateMediaList( getMediaListUrl );
		Thread thread = new Thread( null, this.doBackgroundThreadProcessing, "Background");
		
		// start the thread
		thread.start();
		
		return Service.START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	public VmixVideos getVideos() {
	
		return this.videos;
		
	}
	
	// define background runnable
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		public void run() {
			performGetMediaList();
		}
	};
	
	/**
	 * execute getMediaList
	 */
	private void performGetMediaList() {
		
		try {
			this.operation = new GetMediaListOperation( this.collectionId );
			
			this.videos = this.operation.process();
			
			if( ! this.videos.isEmpty() ) {
				
				this.onLoadComplete();
			
			}
		}
		catch( VmixException e ) {
			
		}
	}
	
	/**
	 * announce load complete for anyone who listens
	 */
	private void onLoadComplete() {
		
		// create new intent
		Intent intent = new Intent( GetMediaListService.MEDIA_FOUND );
		
		// broadcast
		sendBroadcast( intent );
	}
}
